package com.tron.sync.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tron.sync.commons.BaseController;
import com.tron.sync.commons.IDCardUtil;
import com.tron.sync.commons.TronUtils;
import com.tron.sync.entities.*;
import com.tron.sync.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.midi.Soundbank;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "Synda平台用户")
@RestController
@Slf4j
public class SyndaController extends BaseController {


    @Autowired
    JZUserService jzUserService;

    @Autowired
    JZOrgService jzOrgService;

    @Autowired
    SyndaServiceImpl syndaService;

    @Autowired
    WpsServiceImpl wpsService;

    @Autowired
    WpsOrgService wpsOrgService;

    @Autowired
    WpsUserService wpsUserService;

    @Autowired
    WpsOrgFailService wpsOrgFailService;

    @Value("${levelId1}")
    private String levelId1;

    @Value("${region1}")
    private String region1;

    @Value("${levelId2}")
    private String levelId2;

    @Value("${region2}")
    private String region2;


    @ApiOperation(value = "获取synda用户Token")
    @GetMapping("/getToken")
    public Object getToken() {
        String token = syndaService.getToken();
        return token;
    }


    @ApiOperation(value = "获取本地未同步到Synda平台的用户")
    @GetMapping("/Synda/getUnSyncUser")
    public Result<List<JZUser>> getUnSyncUser(Integer page, Integer size) {

        Page<JZUser> myPage = new Page<>();
        Page<JZUser> userPage = jzUserService.page(myPage, Wrappers.<JZUser>lambdaQuery().eq(JZUser::getSyndaSyncStatus, 0));
        return buildResult(userPage.getRecords(), page, size, userPage.getTotal());
    }

    @ApiOperation(value = "获取本地未同步到Synda平台的机构")
    @GetMapping("/Synda/getUnSyncOrg")
    public Result<List<JZOrg>> getUnSyncOrg(Integer page, Integer size) {
        Page<JZOrg> myPage = new Page<>(page, size);
        Page<JZOrg> orgPage = jzOrgService.page(myPage, Wrappers.<JZOrg>lambdaQuery().eq(JZOrg::getSyndaSyncStatus, 0));
        return buildResult(orgPage.getRecords(), page, size, orgPage.getTotal());
    }

    @ApiOperation(value = "同步本地机构和用户到Synda平台")
    @GetMapping("/Synda/syncOrg")
    public String syncOrg(String name, String parentId, String parentOrgType, String childOrgType) {
        String orgPid;
        //判断顶层机构是否被创建
        JZOrg byName = jzOrgService.getByName(name);
        log.error("++++=================根据name查询机构==========" + byName.toString());
        if (byName != null && !StringUtils.isEmpty(byName.getSyndaId())) {
            log.info("============组织机构已存在==========={}", name);
            //顶层机构已创建
            orgPid = byName.getSyndaId();
            syncUser(name, orgPid);
        } else {
            //创建顶层机构
            log.info("===========调用平台接口创建机构============={}", name);
            OAOrg oaOrg = new OAOrg();
            oaOrg.setSort(1);
            oaOrg.setParentId(parentId);
            oaOrg.setName(name);
            oaOrg.setOrgAlias(TronUtils.getPinYinHeadChar(name)+ UUID.randomUUID().toString().substring(0,5));
            oaOrg.setBrevity(name);
            oaOrg.setLevelID(levelId1);
            oaOrg.setRegion(region1);
            oaOrg.setStatus("actived");
            oaOrg.setOrgType(parentOrgType);
            oaOrg.setInherit("0");
            oaOrg.setOrgCode(TronUtils.getUUID());
            oaOrg.setPathName(name);
            String id = syndaService.saveOrg(oaOrg);
            log.info("创建顶层机构成功============================{}", id);
            orgPid = id;
            log.error("++++=================根据name查询机构==========" + byName.toString());
            if (StringUtils.hasText(id)) {
                log.error("++++=================根据name查询机构==========" + byName.toString());
                byName.setSyndaId(id);
                byName.setSyndaSyncStatus(1);
                jzOrgService.updateById(byName);
            }
            syncUser(name, id);
        }
        //获取子机构或部门
        List<JZOrg> byLikeName = jzOrgService.getByLikeName(name);
        log.info("=============创建子部门 start==============={}", byLikeName.toString());
        for (JZOrg jzOrg : byLikeName) {
            if (!StringUtils.isEmpty(jzOrg.getSyndaId())) {
                //如果子机构或部门已创建
                syncUser(jzOrg.getName(), jzOrg.getSyndaId());
            } else {
                //创建子机构
                OAOrg oaOrg = new OAOrg();
                oaOrg.setSort(1);
                oaOrg.setParentId(orgPid);
                oaOrg.setName(jzOrg.getName());
                oaOrg.setOrgAlias(TronUtils.getPinYinHeadChar(jzOrg.getName()));
                oaOrg.setBrevity(name);
                oaOrg.setLevelID(levelId2);
                oaOrg.setRegion(region2);
                oaOrg.setStatus("actived");
                oaOrg.setOrgType(childOrgType);
                oaOrg.setInherit("0");
                oaOrg.setOrgCode(TronUtils.getUUID());
                oaOrg.setPathName(name);
                System.out.println("=================================" + oaOrg + "=====================" + orgPid);
                String id = syndaService.saveOrg(oaOrg);
                log.info("创建子机构完成================================================={}", id);
                if (!StringUtils.isEmpty(id)) {
                    byName.setSyndaId(id);
                    byName.setSyndaSyncStatus(1);
                    jzOrgService.updateById(byName);
                    syncUser(jzOrg.getName(), id);
                }
            }

        }
        log.info("=============创建子部门 end==============={}", byLikeName.toString());
        return "success";
    }

    @ApiOperation(value = "根据机构名称获取用户")
    @GetMapping("/Synda/getUserByOrgName")
    public Result<List<JZUser>> getUserByOrgName(String name) {
        //根据机构名称获取用户
        List<JZUser> list = jzUserService.list(Wrappers.<JZUser>lambdaQuery().like(JZUser::getOrgName, name));
        return buildResult(list);
    }

    /**
     * 根据
     * @param groupId
     * @param orgName
     */
    public void syncUser(String groupId,String orgName) {
        log.info("》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》开始保存-"+orgName+"-下的用户");
        List<JZUser> byOrgName = jzUserService.getByOrgName(orgName);
        log.info("》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》"+orgName+"-下的用户有"+byOrgName);
        if (!byOrgName.isEmpty()){
            byOrgName.forEach(e -> {
                Operator operator = new Operator();
                operator.setRank("yjjy");
                operator.setAccount(e.getCardNo());
                operator.setAddress("");
                operator.setAttrItemList(new JSONArray());
                operator.setBirthday(IDCardUtil.getBirthday(e.getCardNo()));
                operator.setCategory(e.getPoliceCategory());
                operator.setCreateTime("");
                operator.setEmail("");
                operator.setGender(e.getGender());
                operator.setGroupID(groupId);
                operator.setHiredate("");
                operator.setId("");
                operator.setIdNo(e.getCardNo());
                operator.setJob("kc");
                operator.setIdPhoto("");
                operator.setIsSuper("N");
                operator.setMobile(e.getPhoneNo());
                operator.setName(e.getName());
                OrgItem orgItem = new OrgItem();
                orgItem.setId(groupId);
                orgItem.setName(orgName);
                orgItem.setPathName(orgName);
                operator.setOrgItem(orgItem);
                operator.setOrgItem(orgItem);
                operator.setPosItemList(new JSONArray());
                operator.setRoleItemList(new JSONArray());
                operator.setSecretLevel("0");
                operator.setJoinPartyDate("");
                operator.setStatus("actived");
                operator.setTelephone("");
                operator.setInsidePhoto("");
                operator.setType(e.getPoliceType());
                operator.setUserGroupItemList(new JSONArray());
                operator.setUserIdentity("0");
                operator.setUserNumber(e.getPoliceNo());
                operator.setPinyin(TronUtils.getPinYinHeadChar(e.getName()));
                String id = syndaService.saveOperator(operator);
                if (StringUtils.isEmpty(id)) {
                    log.info("》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》"+e.getName()+"-创建完成，id==》》》》"+id);
                    e.setSyndaSyncStatus(1);
                    jzUserService.updateById(e);
                }
            });
        }
    }


    @ApiOperation(value = "获取synda平台机构列表")
    @GetMapping("/getOrgList")
    public List<Map<String, String>> getOrgList() {
        List<Map<String, String>> orgList = syndaService.getOrgList();
        return orgList;
    }

    @ApiOperation(value = "获取synda平台父机构为ORG_ROOT的机构列表")
    @GetMapping("/getFirstFloorOrg")
    public Object getFirstFloorOrg() {
        List<Map<String, String>> orgList = syndaService.getOrgList();
        List<Map<String, String>> collect = orgList.stream().filter(o -> {
            String parentId = o.get("parentId");
            if ("ORG_ROOT".equals(parentId)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return collect;
    }


    @ApiOperation(value = "根据父机构Id为GRG_ROOT的机构同步synda平台机构到------>wps")
    @GetMapping("/syncOrgByOrgId")
    public Object syncOrgByOrgName(String syndaOrgId) {
        Assert.hasText(syndaOrgId, "syndaOrgId不能为空");
        //获取synda全部机构列表
        List<Map<String, String>> syndaOrgList = syndaService.getOrgList();
        //根据机构id过滤出对应的机构
        List<Map<String, String>> mapList = syndaOrgList.stream().filter(e -> {
            if (e.get("id").equals(syndaOrgId)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (mapList.size() > 0) {
            Map<String, String> map = mapList.get(0);
            String id = map.get("id");
            String parentId = map.get("parentId");
            String name = map.get("name");
            WpsOrg wpsOrg = new WpsOrg();
            wpsOrg.setOrgName(name);
            wpsOrg.setSyndaOrgId(id);
            wpsOrg.setSyndaOrgPid(parentId);
            wpsOrg.setWpsOrgPid("root");
            // 创建一级机构
            WpsOrg resultWpsOrg = wpsService.addDept(wpsOrg);
            if (null != resultWpsOrg) {
                log.info("================== 一级部门：[ {}{} ] 创建成功 递归创建子部门 ==================",resultWpsOrg.getWpsOrgId(),resultWpsOrg.getOrgName());
                syncNextFloor(syndaOrgList, resultWpsOrg);
                log.info("================== 一级部门：[ {}{} ] 子部门创建完成 ==================", resultWpsOrg.getWpsOrgId(),resultWpsOrg.getOrgName());
            }
        }
        List<WpsOrgFail> list = wpsOrgFailService.list();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message","同步完成");
        hashMap.put("fail", list.size());
        hashMap.put("failData", list);
        return hashMap;
    }


    //循环添加下一层级
    private void syncNextFloor(List<Map<String, String>> orgList, WpsOrg wpsOrg) {
        //根据父id找到下级机构
        List<Map<String, String>> mapList = orgList.stream().filter(e -> {
            String parentId = e.get("parentId");
            if (parentId != null && parentId.equals(wpsOrg.getSyndaOrgId())) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //循环创建子部门
        if (mapList.size() > 0) {
            mapList.forEach(e -> {
                String id = e.get("id");
                String name = e.get("name");
                String parentId = e.get("parentId");
                WpsOrg childrenWpsOrg = new WpsOrg();
                childrenWpsOrg.setSyndaOrgId(id);
                childrenWpsOrg.setSyndaOrgPid(parentId);
                childrenWpsOrg.setWpsOrgPid(wpsOrg.getWpsOrgId());
                childrenWpsOrg.setOrgName(name);
                WpsOrg resultWpsOrg = null;
                try {
                    log.info("********************** 创建部门 [ {}{} ]-------子部门 [ {} ] ******************", wpsOrg.getWpsOrgId(), wpsOrg.getOrgName(), name);
                    resultWpsOrg = wpsService.addDept(childrenWpsOrg);
                    log.info("[ {}{} ] 子部门：[ {}{} ] 创建成功", wpsOrg.getWpsOrgId(), wpsOrg.getOrgName(), resultWpsOrg.getWpsOrgId(), resultWpsOrg.getOrgName());
                    // 删除失败记录
                    wpsOrgFailService.removeById(resultWpsOrg.getSyndaOrgId());
                } catch (Exception exception) {
                    log.error("子部门：[ {} ] 创建失败： {}", childrenWpsOrg, exception.getMessage());
                    // 创建失败保存记录
                    WpsOrgFail wpsOrgFail = new WpsOrgFail();
                    BeanUtils.copyProperties(childrenWpsOrg,wpsOrgFail);
                    wpsOrgFailService.save(wpsOrgFail);
                }
                //递归创建下一层
                if (null != resultWpsOrg) {
                    log.info("================== 创建部门 [ {}{} ]  下级部门 ==================", resultWpsOrg.getWpsOrgId(), resultWpsOrg.getOrgName());
                    syncNextFloor(orgList, resultWpsOrg);
                    log.info("================== [ {}{} ] 下级部门创建完成 ==================", resultWpsOrg.getWpsOrgId(), resultWpsOrg.getOrgName());
                }
            });
        }
    }

    @ApiOperation(value = "根据机构id同步synda平台用户到------>wps")
    @GetMapping("/syncUserByOrgId")
    public Object syncUserByOrgId(String syndaOrgId) {
        ArrayList<WpsUser> failWpsUsers = new ArrayList<>();
        //获取synda平台用户列表
        List<Map<String, String>> syndaUserList = syndaService.getUserListByOrg(syndaOrgId);
        //根据synda平台机构id查询wps平台机构id
        syndaUserList.forEach(e -> {
            String name = e.get("name");
            String cardNo = e.get("cardNo");
            String serviceSyndaOrgId = e.get("orgId");
            String syndaUserId = e.get("id");
            WpsOrg localWpsOrg = wpsOrgService.getById(serviceSyndaOrgId);
            //如果创建wps用户的必要条件都有，创建wps用户
            if (null != localWpsOrg && StringUtils.hasText(name) && StringUtils.hasText(cardNo) && StringUtils.hasText(syndaUserId)) {
                WpsUser wpsUser = new WpsUser();
                wpsUser.setSyndaUserId(syndaUserId);
                wpsUser.setUserName(name);
                wpsUser.setCardNo(cardNo);
                wpsUser.setSyndaOrgId(serviceSyndaOrgId);
                //创建wps用户，创建成功返回用户,失败返回null
                try {
                    wpsService.addCompanyUser(wpsUser);
                } catch (Exception exception) {
                    log.error("创建用户失败：{}",exception.getMessage());
                    failWpsUsers.add(wpsUser);
                }
            }
        });
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message", "同步完成");
        hashMap.put("fail", failWpsUsers.size());
        hashMap.put("data", failWpsUsers);
        return hashMap;
    }

    @ApiOperation(value = "同步警综平台数据到synda-----hzy")
    @GetMapping("/syncOrgAndUser")
    public String syncOrgAndUser(String orgParentId, String zzjgYwxt,String parentOrgType, String childOrgType){
        //1. 根据zzjgYwxt查询第一个，然后创建
        QueryWrapper<JZOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("zzjg_ywxt",zzjgYwxt);
        List<JZOrg> jzOrgs = jzOrgService.list(queryWrapper);
        JZOrg jzOrg = new JZOrg();
        //需要导入的子机构的父级ID
        String parentId = "";
        if (!jzOrgs.isEmpty()){
            jzOrg = jzOrgs.get(0);
            log.info("开始创建父级机构");
            parentId = saveOrg(jzOrg,orgParentId,zzjgYwxt,parentOrgType,jzOrg.getOrgParentName());
            log.info("父级机构创建成功id================"+parentId);
        }
        if (!StringUtils.isEmpty(parentId)){
            jzOrg.setSyndaId(parentId);
            jzOrgService.updateById(jzOrg);
            //创建用户
            syncUser(parentId,jzOrg.getName());
            QueryWrapper<JZOrg> child = new QueryWrapper<>();
            child.eq("jigdm",zzjgYwxt);
            List<JZOrg> childs = jzOrgService.list(child);
            if (!childs.isEmpty()){
                saveChild(childs,parentId,"2");
            }
        }
        return "success";
    }
    public boolean saveChild(List<JZOrg> jzOrgs,String parentId,String childType){
        for (JZOrg jzOrg : jzOrgs){
            JZOrg jzOrg1 =  jzOrgService.getById(jzOrg.getId());
            if (StringUtils.isEmpty(jzOrg1.getSyndaId())){
                String  id = saveOrg(jzOrg,parentId,jzOrg.getZzjgYwxt(),childType,jzOrg.getOrgParentName());
                syncUser(id,jzOrg.getName());
                if (!StringUtils.isEmpty(id)){
                    jzOrg.setSyndaId(id);
                    jzOrgService.updateById(jzOrg);
                    List<JZOrg> jzOrgs1 =  getOrgChildList(jzOrg.getZzjgYwxt());
                    if (!jzOrgs1.isEmpty()){
                        saveChild(jzOrgs1,id,"3");
                    }
                }
            }
        }
        return true;
    }

    public List<JZOrg> getOrgChildList(String zzjgYwxt){
        QueryWrapper<JZOrg> child = new QueryWrapper<>();
        child.eq("jigdm",zzjgYwxt);
        List<JZOrg> childs = jzOrgService.list(child);
        return childs;
    }

    public String saveOrg(JZOrg jzOrg,String orgParentId, String zzjgYwxt, String orgType,String parentName){
        OAOrg oaOrg = new OAOrg();
        oaOrg.setSort(1);
        oaOrg.setParentId(orgParentId);
        oaOrg.setName(jzOrg.getName());
        oaOrg.setOrgAlias(TronUtils.getPinYinHeadChar(jzOrg.getName()));
        oaOrg.setBrevity(jzOrg.getName());
        oaOrg.setLevelID(levelId2);
        oaOrg.setRegion(region2);
        oaOrg.setStatus("actived");
        oaOrg.setOrgType(orgType);
        oaOrg.setInherit("0");
        oaOrg.setOrgCode(zzjgYwxt);
        oaOrg.setPathName(jzOrg.getName());
        oaOrg.setAttribute("1");
        oaOrg.setOrgPid("");
        String id  = syndaService.saveOrg(oaOrg);
        return id;
    }
}
